﻿using System;
using System.Text.RegularExpressions;

namespace WikiPlex.Contrib.Console
{
    public class Arguments
    {
        private static readonly Regex CommandParser = new Regex(@"(?i)/(?<command>[a-z]+)[=:](?<value>.+)", RegexOptions.Compiled);
        private static readonly Regex ValueParser = new Regex(@"'(?<value>[^']+)'|""(?<value>[^""]+)""|(?<value>.+)", RegexOptions.Compiled);

        private Arguments()
        {
            SourceFilePattern = "*.wiki";
        }

        public bool DisplayHelp { get; private set; }
        public string SourceFilePattern { get; private set; }
        public string SourceFolder { get; private set; }
        public string OutputFolder { get; private set; }
        public string TemplateLocation { get; set; }

        public static Arguments Parse(string[] args)
        {
            var arguments = new Arguments();
            string temp;

            if (args.Length <= 1
                || GetCommand(args[args.Length - 2], out temp) != null
                || GetCommand(args[args.Length - 1], out temp) != null)
            {
                arguments.DisplayHelp = true;
                return arguments;
            }

            for (int i = 0; i < args.Length - 2; i++)
            {
                string value;
                string command = GetCommand(args[i], out value);

                switch (command)
                {
                    case "p":
                    case "pattern":
                        arguments.SourceFilePattern = value;
                        break;
                    case "t":
                    case "template":
                        arguments.TemplateLocation = value;
                        break;
                }
            }

            arguments.SourceFolder = GetValue(args[args.Length - 2]);
            arguments.OutputFolder = GetValue(args[args.Length - 1]);

            return arguments;
        }

        private static string GetCommand(string input, out string value)
        {
            Match match = CommandParser.Match(input);
            if (match.Success)
            {
                value = GetValue(match.Groups["value"].Value);
                return match.Groups["command"].Value;
            }

            value = null;
            return null;
        }

        private static string GetValue(string input)
        {
            Match match = ValueParser.Match(input);
            return match.Success ? match.Groups["value"].Value : null;
        }
    }
}